package com.ginage.gaugemanager.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ginage.gaugemanager.mapper.IGaugeDao;
import com.ginage.gaugemanager.mapper.entity.Department;
import com.ginage.gaugemanager.mapper.entity.Gauge;
import com.ginage.gaugemanager.mapper.entity.GaugeType;
import com.ginage.gaugemanager.service.api.IGaugeService;
import com.ginage.gaugemanager.utils.DateUtil;
import com.ginage.gaugemanager.utils.PageUtil;


@Service("gaugeService")
public class GaugeServiceImpl implements IGaugeService {
	@Autowired
	private IGaugeDao dao;

	/****
	 * 新增量具
	 * 
	 * @param Gauge 要增加的量具
	 * 
	 */
	@Override

	public String addGauge(Gauge gauge) { // 如果存在一个相同的量具编号,就返回-1
		Gauge newGauge = gauge;
		if (isExist(gauge) > 0) {
			return "-1";
		}
		String dateOfAcceptance = gauge.getDateOfAcceptance();
		String dateOfLastCalibration = gauge.getDateOfLastCalibration();
		SimpleDateFormat sdf = null;
		if (dateOfAcceptance.contains("-")) {
			sdf = new SimpleDateFormat("yyyy-MM-dd");
		} else if (dateOfAcceptance.contains("/")) {
			sdf = new SimpleDateFormat("yyyy/MM/dd");
		}
		Date date = null;
		try {
			date = sdf.parse(dateOfLastCalibration);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar c = Calendar.getInstance(); // 使用Date设置日历,再让日历加上月份
		int month = newGauge.getGaugeCalibratePeriod();
		c.setTime(date);
		c.add(Calendar.MONTH, month);
		newGauge.setDateOfAcceptance(DateUtil.dateToTimestamp(dateOfAcceptance));
		newGauge.setDateOfLastCalibration(DateUtil.dateToTimestamp(dateOfLastCalibration));
		newGauge.setDateOfNextCalibration(String.valueOf(c.getTimeInMillis()));
		String factory = getFactory(newGauge.getDepartmentNum());
		newGauge.setFactory(factory);
		int num = dao.getGaugeMaxNum(newGauge) + 1;
		newGauge.setOrderNum(num);
		String orderNum = null;
		if (num / 10 == 0) {
			orderNum = "000" + num;
		} else if (num / 100 == 0) {
			orderNum = "00" + num;
		} else if (num / 1000 == 0) {
			orderNum = "0" + num;
		}
		//如果新增的量具是这几种之一,编码方式不一样
		String[] bigGauge = { "CMM", "VMS", "P", "RHT", "Z", "DFMG", "EPB" };
		String aceNum = gauge.getGaugeNameAbbr() + orderNum + "AM" + gauge.getDepartmentNum();
		for (String s : bigGauge) {
			if (gauge.getGaugeNameAbbr().equals(s)) {
				num=dao.getBigGaugeOrderNum(s)+1;
				if (num / 10 == 0) {
					orderNum = "0" + num;
				} else {
					orderNum = String.valueOf(num);
				}
				aceNum = gauge.getGaugeNameAbbr() + orderNum;
				dao.updateOrderNum(s);
				
			}
		}
		newGauge.setAceNum(aceNum);
		dao.addGauge(newGauge);
		return aceNum;
	}

	@Override
	public int getGaugeMaxNum(Gauge gauge) {
		// TODO Auto-generated method stub
		return dao.getGaugeMaxNum(gauge);

	}

	@Override
	public int isExist(Gauge guage) {
		// TODO Auto-generated method stub

		return dao.isExist(guage);
	}

	@Override
	public JSONArray getAllGaugesByPost() {
		// TODO Auto-generated method stub
		List<Gauge> gaugeList=getAllGauges();
		JSONArray ja=new JSONArray();
		JSONObject jb=new JSONObject();
		for (Gauge gauge :gaugeList) {
			jb.put("aceNum", gauge.getAceNum());
			jb.put("calibrationResult", gauge.getCalibrationResult());
			jb.put("dateOfAcceptance", gauge.getDateOfAcceptance());
			jb.put("dateOfLastCalibration", gauge.getDateOfLastCalibration());
			jb.put("dateOfNextCalibration", gauge.getDateOfNextCalibration());
			jb.put("department", gauge.getDepartment());
			jb.put("factory", gauge.getFactory());
			jb.put("gaugeAccuracy", gauge.getGaugeAccuracy());
			jb.put("gaugeFolder", gauge.getGaugeFolder());
			jb.put("gaugeManufacturer", gauge.getGaugeManufacturer());
			jb.put("gaugeModel", gauge.getGaugeModel());
			jb.put("gaugeName", gauge.getGaugeName());
			jb.put("gaugeNum", gauge.getGaugeNum());
			jb.put("gaugeOwner", gauge.getGaugeOwner());
			jb.put("gaugeRemainingDays", gauge.getGaugeRemainingDays());
			jb.put("gaugeRemark", gauge.getGaugeRemark());
			jb.put("gaugeSpecification", gauge.getGaugeSpecification());
			jb.put("gaugeStatus", gauge.getGaugeStatus());
			jb.put("gaugeCalibratePeriod", gauge.getGaugeCalibratePeriod());
			jb.put("id", gauge.getId());
			
			ja.add(jb);
		}
		
		return ja;
	}

	@Override
	public List getAllGauges() {
		// TODO Auto-generated method stub
		List<Gauge> gaugeList = dao.getAllGauges();
		for (Gauge gauge : gaugeList) {
			gauge.setDateOfAcceptance(DateUtil.timestampToDate(gauge.getDateOfAcceptance()));
			gauge.setDateOfLastCalibration(DateUtil.timestampToDate(gauge.getDateOfLastCalibration()));
			gauge.setDateOfNextCalibration(DateUtil.timestampToDate(gauge.getDateOfNextCalibration()));
			String gaugeName=getGaugeName(gauge.getGaugeNameAbbr());
			String department=getDepartment(gauge.getDepartmentNum());
			String factory=dao.getFactory(gauge.getDepartmentNum());
			gauge.setDepartment(department);
			gauge.setFactory(factory);
			gauge.setGaugeName(gaugeName);

		}
		return gaugeList;
	}

	@Override
	public String getFactory(String departmentNum) {
		// TODO Auto-generated method stub
		return dao.getFactory(departmentNum);
	}

	@Override
	public String getDepartment(String departmentNum) {
		// TODO Auto-generated method stub
		return dao.getDepartment(departmentNum);
	}

	@Override
	public String[] editGauge(Gauge gauge) {
		// TODO Auto-generated method stub
		String[] result = { "", "" };
		Gauge newGauge = gauge;

		String dateOfAcceptance = gauge.getDateOfAcceptance();
		String dateOfLastCalibration = gauge.getDateOfLastCalibration();
		SimpleDateFormat sdf = null;
		if (dateOfAcceptance.contains("-")) {
			sdf = new SimpleDateFormat("yyyy-MM-dd");
		} else if (dateOfAcceptance.contains("/")) {
			sdf = new SimpleDateFormat("yyyy/MM/dd");
		}
		Date date = null;
		try {
			date = sdf.parse(dateOfLastCalibration);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Calendar c = Calendar.getInstance(); // 使用Date设置日历,再让日历加上月份
		int month = newGauge.getGaugeCalibratePeriod();
		c.setTime(date);
		c.add(Calendar.MONTH, month);
		newGauge.setDateOfAcceptance(DateUtil.dateToTimestamp(dateOfAcceptance));
		newGauge.setDateOfLastCalibration(DateUtil.dateToTimestamp(dateOfLastCalibration));
		newGauge.setDateOfNextCalibration(String.valueOf(c.getTimeInMillis()));
		String factory = getFactory(newGauge.getDepartmentNum());
		newGauge.setFactory(factory);
		// 如果量具名称或归属部门发生变化,量具的精英编号就要更改!
		Gauge oldGauge = getGauge(newGauge.getId());
		String oldDepartmentNum = oldGauge.getDepartmentNum();
		String newDepartmentNum = newGauge.getDepartmentNum();
		String oldGaugeNameAbbr = oldGauge.getGaugeNameAbbr();
		String newGaugeNameAbbr = newGauge.getGaugeNameAbbr();
		if (!oldDepartmentNum.contentEquals(newDepartmentNum) || !oldGaugeNameAbbr.contentEquals(newGaugeNameAbbr)) {
			int num = dao.getGaugeMaxNum(newGauge) + 1;
			newGauge.setOrderNum(num);
			String orderNum = null;
			if (num / 10 == 0) {
				orderNum = "000" + num;
			} else if (num / 100 == 0) {
				orderNum = "00" + num;
			} else if (num / 1000 == 0) {
				orderNum = "0" + num;
			}
			// 如果新增的量具是这几种之一,编码方式不一样
			String[] bigGauge = { "CMM", "VMS", "P", "RHT", "Z", "DFMG", "EPB" };
			String aceNum = gauge.getGaugeNameAbbr() + orderNum + "AM" + gauge.getDepartmentNum();
			for (String s : bigGauge) {
				if (gauge.getGaugeNameAbbr().equals(s)) {
					if (num / 10 == 0) {
						orderNum = "0" + num;
					} else {
						orderNum = String.valueOf(num);
					}
					aceNum = gauge.getGaugeNameAbbr() + orderNum;
				}
			}
			newGauge.setAceNum(aceNum);
			result[1] = "新的精英编号为:" + aceNum;
		}
		if (dao.editGauge(newGauge) > 0) {
			result[0] = "s";
		}
		return result;
	}

	@Override
	public int removeGauge(int[] ids) {
		// TODO Auto-generated method stub

		return dao.removeGauge(ids);
	}

	@Override
	public Gauge getGauge(int id) {
		// TODO Auto-generated method stub
		return dao.getGauge(id);
	}

	@Override
	public JSONArray searchGauge(Gauge searchGauge,int currentPage) {
		int total=dao.getTotal(searchGauge);
		PageUtil p= new PageUtil(total,20,currentPage);
		List<Gauge> gaugeList=dao.searchGauge(searchGauge,p.getStartPos(),p.getEndPos());
		for (Gauge gauge : gaugeList) {
			gauge.setDateOfAcceptance(DateUtil.timestampToDate(gauge.getDateOfAcceptance()));
			gauge.setDateOfLastCalibration(DateUtil.timestampToDate(gauge.getDateOfLastCalibration()));
			gauge.setDateOfNextCalibration(DateUtil.timestampToDate(gauge.getDateOfNextCalibration()));
			String gaugeName=getGaugeName(gauge.getGaugeNameAbbr());
			String department=getDepartment(gauge.getDepartmentNum());
			String factory=dao.getFactory(gauge.getDepartmentNum());
			gauge.setDepartment(department);
			gauge.setFactory(factory);
			gauge.setGaugeName(gaugeName);
		}
		JSONArray ja=new JSONArray();
		JSONObject jbTotal=new JSONObject();
		jbTotal.put("total", total);
		jbTotal.put("currentPage", p.getCurrentPage());
		jbTotal.put("totalPage", p.getTotalPageCount());
		jbTotal.put("eachPageCount", p.getEachPageCount());
		ja.add(jbTotal);
		for (Gauge gauge :gaugeList) {
			JSONObject jb=new JSONObject();
			jb.put("aceNum", gauge.getAceNum());
			jb.put("calibrationResult", gauge.getCalibrationResult());
			jb.put("dateOfAcceptance", gauge.getDateOfAcceptance());
			jb.put("dateOfLastCalibration", gauge.getDateOfLastCalibration());
			jb.put("dateOfNextCalibration", gauge.getDateOfNextCalibration());
			jb.put("department", gauge.getDepartment());
			jb.put("factory", gauge.getFactory());
			jb.put("gaugeAccuracy", gauge.getGaugeAccuracy());
			jb.put("gaugeFolder", gauge.getGaugeFolder());
			jb.put("gaugeManufacturer", gauge.getGaugeManufacturer());
			jb.put("gaugeModel", gauge.getGaugeModel());
			jb.put("gaugeName", gauge.getGaugeName());
			jb.put("gaugeNum", gauge.getGaugeNum());
			jb.put("gaugeOwner", gauge.getGaugeOwner());
			jb.put("gaugeRemainingDays", gauge.getGaugeRemainingDays());
			jb.put("gaugeRemark", gauge.getGaugeRemark());
			jb.put("gaugeSpecification", gauge.getGaugeSpecification());
			jb.put("gaugeStatus", gauge.getGaugeStatus());
			jb.put("gaugeCalibratePeriod", gauge.getGaugeCalibratePeriod());
			jb.put("id", gauge.getId());
			ja.add(jb);
		}
		return ja;
	}

	@Override
	public List<Map<String, Object>> getName() {
		// TODO Auto-generated method stub
		return dao.getName();
	}

	@Override
	public JSONObject getGaugeSpecification() {
		// TODO Auto-generated method stub
		String gaugeSpecifications[]=dao.getGaugeSpecification();
		JSONObject jb=new JSONObject();
		for (int i=0;i<gaugeSpecifications.length;i++) {
			jb.put(gaugeSpecifications[i], gaugeSpecifications[i]);
		}
		return jb;
	}

	@Override
	public JSONObject getGaugeAccuracy() {
		// TODO Auto-generated method stub
		String gaugeAccuracy[]=dao.getGaugeAccuracy();
		JSONObject jb=new JSONObject();
		for (int i=0;i<gaugeAccuracy.length;i++) {
			jb.put(gaugeAccuracy[i], gaugeAccuracy[i]);
		}
		return jb;
	}

	@Override
	public JSONObject getGaugeModel() {
		// TODO Auto-generated method stub
		String gaugeModel[]=dao.getGaugeModel();
		JSONObject jb=new JSONObject();
		for (int i=0;i<gaugeModel.length;i++) {
			jb.put(gaugeModel[i], gaugeModel[i]);
		}
		return jb;
	}

	@Override
	public JSONObject getDepartments() {
		// TODO Auto-generated method stub
		String departmentNum[]=dao.getDepartmentNums();
		List<Department> departmentList=dao.getDepartments(departmentNum);
		JSONObject jb=new JSONObject();
		for(Department dept :departmentList) {
			jb.put(dept.getDepartmentNum(), dept.getFactory()+"-"+dept.getDepartmentName());
		}
		return jb;
	}

	@Override
	public JSONObject getGaugeRemainingDays() {
		// TODO Auto-generated method stub
		int gaugeRemainingDays[]=dao.getGaugeRemainingDays();
		JSONObject jb=new JSONObject();
		for (int i=0;i<gaugeRemainingDays.length;i++) {
			/*
			 * long nextDay = Long.parseLong(gaugeRemainingDays[i]); long today = new
			 * Date().getTime(); int days = (int) ((nextDay - today) / 1000 / 60 / 60 / 24);
			 */
			jb.put(gaugeRemainingDays[i]+"", gaugeRemainingDays[i]+"");
		}
		return jb;
	}

	@Override
	public JSONObject getGaugeManufacturer() {
		// TODO Auto-generated method stub
		String gaugeManufacturer[]=dao.getGaugeManufacturer();
		JSONObject jb=new JSONObject();
		for (int i=0;i<gaugeManufacturer.length;i++) {
			jb.put(gaugeManufacturer[i], gaugeManufacturer[i]);
		}
		return jb;
	}

	

	@Override
	public String getGaugeName(String gaugeNameAbbr) {
		// TODO Auto-generated method stub
		return dao.getGaugeName(gaugeNameAbbr);
	}

	@Override
	public JSONObject getGaugeOwner() {
		// TODO Auto-generated method stub
		String gaugeOwner[]=dao.getGaugeOwner();
		JSONObject jb=new JSONObject();
		for (int i=0;i<gaugeOwner.length;i++) {
			jb.put(gaugeOwner[i], gaugeOwner[i]);
		}
		return jb;
	}

	@Override
	public JSONObject getGaugeCalibratePeriod() {
		// TODO Auto-generated method stub
		String gaugeCalibratePeriod[]=dao.getGaugeCalibratePeriod();
		JSONObject jb=new JSONObject();
		for (int i=0;i<gaugeCalibratePeriod.length;i++) {
			jb.put(gaugeCalibratePeriod[i], gaugeCalibratePeriod[i]);
		}
		return jb;
	}

	@Override
	public JSONObject getCalibrationResult() {
		// TODO Auto-generated method stub
		String calibrationResult[]=dao.getCalibrationResult();
		JSONObject jb=new JSONObject();
		for (int i=0;i<calibrationResult.length;i++) {
			jb.put(calibrationResult[i], calibrationResult[i]);
		}
		return jb;
	}

	@Override
	public JSONObject getGaugeStatus() {
		// TODO Auto-generated method stub
		String gaugeStatus[]=dao.getGaugeStatus();
		JSONObject jb=new JSONObject();
		for (int i=0;i<gaugeStatus.length;i++) {
			jb.put(gaugeStatus[i], gaugeStatus[i]);
		}
		return jb;
	}

	@Override
	public JSONObject getGaugeFolder() {
		// TODO Auto-generated method stub
		String gaugeFolder[]=dao.getGaugeFolder();
		JSONObject jb=new JSONObject();
		for (int i=0;i<gaugeFolder.length;i++) {
			jb.put(gaugeFolder[i], gaugeFolder[i]);
		}
		return jb;
	}

	@Override
	public JSONObject getGaugeNames() {
		// TODO Auto-generated method stub
		JSONObject jb=new JSONObject();
		String [] gaugeNameAbbrs=dao.getGaugeNameAbbrs();
		List<GaugeType> GaugeTypeList=dao.getGaugeNamesByAbbrs(gaugeNameAbbrs);
		for(GaugeType gt:GaugeTypeList) {
			jb.put(gt.getAbbreviation(), gt.getGaugeName());
		}
		
		return jb;
	}

	@Override
	public JSONObject getOverViewInfo() {
		int totalOfNeedToCalibrateThisMonth=dao.getTotalOfNeedToCalibrateThisMonth();
		int totalOfExpired=dao.totalOfExpired();
		int totalOfLost=dao.totalOfLost();
		int totalOfScrapped=dao.totalOfScrapped();
		int totalOfGauge=dao.totalOfGauge();
		int totalOfBigGauge=dao.totalOfBigGauge();
		int totalOfCommonGauge=dao.totalOfCommonGauge();
		JSONObject jb=new JSONObject();
		jb.put("totalOfNeedToCalibrateThisMonth",totalOfNeedToCalibrateThisMonth+"");
		jb.put("totalOfExpired",totalOfExpired+"");
		jb.put("totalOfLost",totalOfLost+"");
		jb.put("totalOfScrapped",totalOfScrapped+"");
		jb.put("totalOfGauge",totalOfGauge+"");
		jb.put("totalOfBigGauge",totalOfBigGauge+"");
		jb.put("totalOfCommonGauge",totalOfCommonGauge+"");
		return jb;
	}

}
